import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import router from 'umi/router';
import { routerRedux, Route, Switch } from 'dva/router';
import Media from 'react-media';
import { Row, Col, Form, Input, Select, Button, DatePicker } from 'antd';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import DriverDetails from './DriverDetails';
import prompt from '@/components/Prompt';
import AdSearch from '@/components/AdSearch';
import SelectForm from '@/components/SelectForm';
import ManageList from '@/components/ManageList';
import TableButtons from '@/components/TableButtons';
import RightDraw from '@/components/RightDraw';
import AdButton from '@/components/AdButton';
import { codes } from './utils';
import AdSelect from '@/components/AdSelect';
import { formateDateToMin } from '@/utils/common';
const FormItem = Form.Item;
const { TextArea } = Input;
const { Option } = Select;

@ManageList
@connect(({ tmsDriver, component, common, loading }) => ({
  tmsDriver,
  ownCompany: common.ownCompany,
  searchValue: component.searchValue,
  loading: loading.effects['tmsDriver/selectList'],
  dictObject: common.dictObject,
}))
@Form.create()
export default class DriverList extends Component {
  state = {
    updateModalVisible: false,
    expandForm: false,
    selectedRows: [],
    stepFormValues: {},
    visible: false,
    checkId: '',
    checkIds: [],
    formValues: {},
    vehicleAbled: '',
  };
  className = 'DriverList';
  columns = [
    {
      title: '姓名',
      dataIndex: 'name',
      render: (text, record) => (
        <AdButton
          mode="a"
          onClick={e => this.showDetail(e, record.id)}
          text={text}
          code={codes.showDetail}
        />
      ),
      fixed: this.props.isMobile ? false : true,
    },
    {
      title: '英文名',
      dataIndex: 'engName',
    },
    {
      title: '工号',
      dataIndex: 'workerNo',
      width: 100,
    },
    {
      title: '身份证号',
      dataIndex: 'idCard',
      width: 200,
    },
    {
      title: '公司',
      dataIndex: 'mdsCompanyName',
      width: 250,
      render: text => <span title={text}>{text}</span>,
    },
    {
      title: '准驾车型',
      dataIndex: 'allowVehicleType',
      render: text => (
        <AdSelect
          onlyRead={true}
          value={text}
          data={this.props.dictObject['allow-vehicle-models']}
        />
      ),
      width: 100,
    },
    {
      title: '电话1',
      dataIndex: 'phoneNumOne',
    },
    {
      title: '微信号',
      dataIndex: 'wxNo',
    },
    {
      title: '状态',
      dataIndex: 'beActive',
      render: (text, record) => <span>{text ? '启用' : '禁用'}</span>,
      width: 100,
    },
    {
      title: '创建人',
      dataIndex: 'createBy',
      render: text => (
        <AdSearch
          label="loginName"
          name="sysName"
          value={this.props.searchValue[text]}
          onlyRead={true}
        />
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      render: text => <span>{text ? moment(text).format(formateDateToMin) : ''}</span>,
    },
    {
      title: '更新人',
      dataIndex: 'updateBy',
      render: text => (
        <AdSearch
          label="loginName"
          name="sysName"
          value={this.props.searchValue[text]}
          onlyRead={true}
        />
      ),
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      render: text => <span>{text ? moment(text).format(formateDateToMin) : ''}</span>,
    },
  ];

  componentDidMount() {
    this.getSelectList();
    // 查询字典：
    // 准驾车型
    this.props.dispatch({
      type: 'common/querytDictByCode',
      payload: { code: 'allow-vehicle-models' },
    });
  }

  onRef = ref => {
    this.child = ref;
  };

  getSelectList = val => {
    const { dispatch, searchValue } = this.props;
    let params = val || {};
    dispatch({
      type: 'tmsDriver/selectList',
      payload: params,
      callback: data => {
        if (!data) return;
        let valueList = [];
        data.map(v => {
          const labels = ['updateBy', 'createBy'];
          labels.map(item => {
            if (v[item] && !valueList.includes(v[item])) {
              valueList.push(v[item]);
              !searchValue[v[item]] &&
                dispatch({
                  type: 'component/querySearchValue',
                  payload: {
                    params: { loginName: v[item] },
                    url: 'tms/tms-vehicle/selectDrivderUser_s',
                  },
                });
            }
          });
        });
      },
    });
  };

  //重置
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    this.getSelectList();
  };

  toggleForm = expandForm => {
    this.setState({
      expandForm,
    });
  };

  handleSelectRows = rows => {
    // console.log('选择', rows);
    let ids = [];
    if (Array.isArray(rows) && rows.length > 0) {
      rows.map((item, i) => {
        ids.push(item.id);
      });
    }
    this.setState({
      selectedRows: rows,
      checkIds: ids,
    });
  };

  //查询
  handleSearch = values => {
    if (!values) {
      return;
    }
    const { ...value } = values;
    this.setState({
      formValues: value,
    });
    this.getSelectList(value);
  };

  //新建
  handleAdd = () => {
    const { dispatch } = this.props;
    router.push(`/carBasic/driverList/add-form`);
  };
  //编辑：
  handleEdit = () => {
    router.push(`/carBasic/driverList/edit-form/${this.state.checkId}`);
    this.closeDetail();
  };
  // 分页操作：改参数
  handleStandardTableChange = param => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const params = {
      ...formValues,
      ...param,
    };

    this.getSelectList(params);
  };
  //详情：
  showDetail = (e, id) => {
    e.stopPropagation();
    const { dispatch } = this.props;
    dispatch({
      type: 'tmsDriver/selectDetails',
      payload: { id: id },
    });
    // dispatch({
    //   type: 'tmsDriver/viewPapersDetails',
    //   payload: { id: id },
    // });
    this.setState(
      {
        checkId: id,
      },
      () => {
        this.setState({
          visible: true,
        });
      }
    );
  };

  closeDetail = () => {
    this.setState({
      visible: false,
    });
  };

  //启用、禁用：
  useVehicleType = (type, single) => {
    const { dispatch } = this.props;
    const { checkIds, checkId } = this.state;
    const params = {};
    params.ids = single ? [checkId] : checkIds;
    params.type = type == 'disabled' ? false : true;
    dispatch({
      type: 'tmsDriver/ableDriverOperate',
      payload: params,
      callback: res => {
        if (single) {
          this.setState({
            vehicleAbled: type == 'disabled' ? false : true,
          });
          dispatch({
            type: 'tmsDriver/selectDetails',
            payload: { id: checkId },
          });
        } else {
          dispatch({
            type: 'tmsDriver/selectList',
            payload: this.state.formValues,
          });
        }
      },
    });
  };

  print = () => {
    window.document.body.innerHTML = window.document.getElementById('driverList').innerHTML;
    window.print();
    window.location.reload();
  };

  render() {
    const {
      form,
      loading,
      tmsDriver: { selectList, selectDetails },
      isMobile,
      ownCompany,
    } = this.props;
    const { getFieldDecorator } = form;
    const {
      selectedRows,
      updateModalVisible,
      stepFormValues,
      vehicleAbled,
      checkId,
      visible,
      expandForm,
    } = this.state;
    const details = selectDetails && checkId ? selectDetails[checkId] : {};
    const vehicleAbled_check = vehicleAbled !== '' ? vehicleAbled : details && details.beActive;

    const firstFormItem = (
      <FormItem label="司机姓名">
        {getFieldDecorator('name')(<Input placeholder="请输入司机姓名" />)}
      </FormItem>
    );
    const secondFormItem = (
      <FormItem label="联系电话">
        {getFieldDecorator('phoneNumOne')(<Input placeholder="请输入联系电话" />)}
      </FormItem>
    );

    // secondForm 参数
    const otherFormItem = [
      [
        <FormItem label="公司">
          {getFieldDecorator('mdsCompanyId')(
            <Select
              allowClear={true}
              style={{ width: '100%' }}
              showSearch
              filterOption={(input, option) =>
                option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
              }
              placeholder="请选择"
            >
              <Option value="">请选择</Option>
              {ownCompany &&
                ownCompany.map((v, i) => {
                  return (
                    <Option key={i} value={v.customerCode}>
                      {v.customerName}
                    </Option>
                  );
                })}
            </Select>
          )}
        </FormItem>,
      ],
      [
        <FormItem label="工号">
          {getFieldDecorator('workerNo')(<Input placeholder="请输入工号" />)}
        </FormItem>,

        'operatorButtons',
      ],
    ];
    const selectFormParams = {
      firstFormItem,
      secondFormItem,
      otherFormItem,
      form,
      code: codes.select,
      className: this.className,
      handleFormReset: this.handleFormReset,
      handleSearch: this.handleSearch,
      toggleForm: this.toggleForm,
    };
    const tableButtonsParams = {
      show: true,
      handleAdd: this.handleAdd,
      code: codes.add,
      buttons: (
        <Button.Group>
          <AdButton
            onClick={() => this.useVehicleType('disabled')}
            disabled={selectedRows.length > 0 ? false : true}
            text="禁用"
            code={codes.disable}
            selectedRows={selectedRows}
          />
          <AdButton
            onClick={() => this.useVehicleType('abled')}
            disabled={selectedRows.length > 0 ? false : true}
            text="启用"
            code={codes.enable}
            selectedRows={selectedRows}
          />
        </Button.Group>
      ),
      selectedRows: selectedRows,
    };

    const rightDrawParams = {
      isMobile,
      visible,
      title: '司机详情',
      closeDetail: this.closeDetail,
      code: codes.showDetail,
      buttons: (
        <span>
          <Button.Group>
            {!vehicleAbled_check && (
              <AdButton
                onClick={() => this.useVehicleType('abled', 1)}
                text="启用"
                code={codes.enable}
              />
            )}
            {vehicleAbled_check && (
              <AdButton
                onClick={() => this.useVehicleType('disabled', 1)}
                text="禁用"
                code={codes.disable}
              />
            )}
            <AdButton type="primary" onClick={this.handleEdit} text="编辑" code={codes.edit} />
          </Button.Group>
        </span>
      ),
    };
    return (
      <Fragment>
        <SelectForm {...selectFormParams} />
        <TableButtons {...tableButtonsParams} />
        <StandardTable
          selectedRows={selectedRows}
          loading={loading}
          data={selectList}
          columns={this.columns}
          onSelectRow={this.handleSelectRows}
          onPaginationChange={this.handleStandardTableChange}
          expandForm={expandForm}
          className={this.className}
          code={codes.page}
        />
        <RightDraw {...rightDrawParams}>
          <DriverDetails checkId={checkId} isMobile={isMobile} />
        </RightDraw>
      </Fragment>
    );
  }
}
